package com.ocom.app.config;

import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.StringUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
//@Component
public class WxAuthInterceptor implements RequestInterceptor {

  @Autowired
  private StringRedisTemplate redisTemplate;

  private String authHost = "http://192.168.11.59:8082/";

  @Override
  public void apply(RequestTemplate requestTemplate) {

    String telephone = "18675566137";

    Map<String, Collection<String>> queries = requestTemplate.queries();
    if (!ObjectUtils.isEmpty(queries)) {
      Object[] openId = queries.get("openid").toArray();
      telephone = (String) openId[0];
      System.out.println(telephone);
    }
    if (!ObjectUtils.isEmpty(requestTemplate.body())) {
      String body = new String(requestTemplate.body());

      if (!StringUtil.isEmpty(body)) {
        telephone = JSON.parseObject(body).getString("openid");
      }
    }

    String token = null;
    try {
      token = getAuthorization(telephone);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    requestTemplate.header(HttpHeaders.AUTHORIZATION, token);
  }

  private String getAuthorization(String telephones) throws Exception {
    String key = String.format("app:wxtoken:%s", telephones);
    String token = redisTemplate.opsForValue().get(key);
    if (StringUtil.isEmpty(token)) {
      //调登录接口
      token = login(telephones);
    }

    return token;

  }

  public String login(String telephones) throws Exception {

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> formBody = new LinkedMultiValueMap<>();
    formBody.add("wx_code", telephones);
    formBody.add("grant_type", "wx_auth");
    formBody.add("client_id", "client_2");
    formBody.add("client_secret", "123456");

    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formBody, headers);
    ResponseEntity<Map> response = restTemplate.exchange(authHost + "/auth/login", HttpMethod.POST, entity, Map.class);

    Map body = response.getBody();
    Integer code = (Integer) body.get("code");
    if (response.getStatusCode() == HttpStatus.OK && code == 200) {
      Map data = (Map) body.get("data");
      String token = "bearer " + (String) data.get("skey");

      Integer exp = (Integer) data.get("exp");
      String key = String.format("app:wxtoken:%s", telephones);
      redisTemplate.opsForValue().set(key, token, Long.valueOf(71000), TimeUnit.SECONDS);
      return token;

    }

    throw new Exception("App接口失败");


  }
}
